<template>
  <div style="position: relative;">
    <label><input class="show-path" :placeholder="placeholder" v-model="filePath"></label>
    <div class="file-icon" @click="fileSelectClick">
      <svg class="file-icon-img" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
        <path
            d="M394.397538 157.538462l118.193231 78.76923H787.692308a78.769231 78.769231 0 0 1 78.76923 78.769231v472.615385a78.769231 78.769231 0 0 1-78.76923 78.76923H236.307692a78.769231 78.769231 0 0 1-78.76923-78.76923V236.307692a78.769231 78.769231 0 0 1 78.76923-78.76923h158.089846zM827.076923 472.615385H196.923077v315.076923a39.384615 39.384615 0 0 0 34.776615 39.108923L236.307692 827.076923h551.384616a39.384615 39.384615 0 0 0 39.108923-34.776615L827.076923 787.692308v-315.076923zM382.464 196.923077H236.307692a39.384615 39.384615 0 0 0-39.108923 34.776615L196.923077 236.307692v196.923077h630.153846V315.076923a39.384615 39.384615 0 0 0-34.776615-39.108923L787.692308 275.692308h-275.101539a39.384615 39.384615 0 0 1-17.841231-4.253539l-4.01723-2.363077L382.464 196.923077z"></path>
      </svg>
    </div>
  </div>
</template>

<script>
const {dialog} = window.electron;

export default {
  name: "FileSelect",
  model: {
    prop: 'path',
    event: 'change',
  },
  props: {
    placeholder: {
      type: String
    },
    path: {
      type: String
    },
    type: {
      type: String,
      default: 'file'
    },
    multiSelections: {
      type: Boolean,
      default: false
    },
    filters: {
      type: Array,
      default() {
        return [
          {name: 'All Files', extensions: ['*']}
        ]
      }
    }
  },
  data() {
    return {
      filePath: ""
    }
  },
  created() {
    this.filePath = this.path
  },
  methods: {
    async fileSelectClick() {
      let properties = [];
      properties[0] = this.type === "directory" ? 'openDirectory' : 'openFile';
      this.multiSelections && (properties[1] = "multiSelections");
      let path = await dialog.showOpenDialog({
        defaultPath: this.filePath,
        filters: this.filters,
        properties,
      });
      !path.canceled && (this.filePath = path.filePaths[0]);
    }
  },
  watch: {
    filePath(newValue) {
      this.$emit('change', newValue)
    }
  }
}
</script>

<style scoped>
.show-path {
  box-sizing: border-box;
  width: 100%;
  padding: 2px 30px 2px 4px;
  height: 28px;
  outline: none;
  border: 1px solid var(--color-border);
  border-radius: 4px;
}

.file-icon {
  width: 30px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  top: 0;
  right: 0;
}

.file-icon-img {
  width: 22px;
  height: 22px;
  fill: var(--color-border);
}

</style>